<template>
  <div id="login">
    <div class="title">管理系统</div>
    <div class="login-wrap">
      <ul class="menu-tab">
        <li
          :class="{ current: item.current }"
          v-for="item in menuTab"
          :key="item.id"
          @click="toggleMenu(item)"
        >
          {{ item.txt }}
        </li>
      </ul>
      <el-form
        :model="ruleForm"
        status-icon
        :rules="rules"
        ref="ruleForm"
        class="login-form"
      >
        <!-- 输入邮箱账号 -->
        <el-form-item prop="userName" class="item-form">
          <label for="userName">邮箱</label>
          <el-input
            id="userName"
            type="text"
            v-model="ruleForm.userName"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item prop="password" class="item-form">
          <label for="password">密码</label>
          <el-input
            id="password"
            v-model="ruleForm.password"
            minlength="6"
            maxlength="20"
            type="password"
          ></el-input>
        </el-form-item>
        <!-- 重复密码 -->
        <el-form-item
          prop="passwords"
          class="item-form"
          v-if="mode == 'register'"
        >
          <label for="passwords">重复密码</label>
          <el-input
            id="passwords"
            v-model="ruleForm.passwords"
            minlength="6"
            maxlength="20"
            type="password"
          ></el-input>
        </el-form-item>
        <!-- 获取验证码 -->
        <el-form-item prop="code" class="item-form">
          <label for="code">验证码</label>
          <el-row :gutter="10">
            <el-col :span="15">
              <el-input
                id="code"
                type="text"
                v-model="ruleForm.code"
                autocomplete="off"
                maxlength="6"
                minlength="6"
              ></el-input>
            </el-col>
            <el-col :span="9">
              <el-button
                type="success"
                class="block"
                @click="getVerifyCode()"
                :disabled="getCodeStar.buttonSatr"
                >{{ getCodeStar.buttonName }}</el-button
              >
            </el-col>
          </el-row>
        </el-form-item>
        <!-- 提交表单 -->
        <el-form-item>
          <el-button
            class="block login-button"
            :disabled="loginButtonStart"
            type="danger"
            @click="submitForm('ruleForm')"
            size="medium"
            >{{ mode == "login" ? "登陆" : "注册" }}</el-button
          >
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import sha1 from "sha1";
import {
  stripscript,
  validatePass,
  validateEmail,
  validateVCode
} from "@/utils/verify";
import { reactive, ref, onMounted } from "@vue/composition-api";
import { getSms, register } from "@/network/api/login.js";
export default {
  name: "login",
  // 这里放置 data数据  生命周期函数  自定义事件
  // 用于替换2.0中的data
  setup(props, { refs, root }) {
    // root: (...) ===>this
    // parent: (...)
    // refs: (...)
    // attrs: (...)
    // listeners: (...)
    // isServer: (...)
    // ssrContext: (...)
    // emit: (...)
    /**
     *表单验证
     */
    let validateUserName = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入用户名"));
      } else if (validateEmail(value)) {
        callback(new Error("输入的邮箱格式有误"));
      } else {
        callback();
      }
    };
    let validatePassword = (rule, value, callback) => {
      ruleForm.password = stripscript(value);
      value = ruleForm.password;
      if (value === "") {
        callback(new Error("请输入密码"));
      } else if (validatePass(value)) {
        callback(new Error("输入的密码格式有误"));
      } else {
        callback();
      }
    };
    let validatePasswords = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入再次输入密码"));
      } else if (value != ruleForm.password) {
        callback(new Error("输入的密码格式有误"));
      } else {
        callback();
      }
    };

    let validateCode = (rule, value, callback) => {
      ruleForm.code = stripscript(value);
      value = ruleForm.code;
      if (value == "") {
        return callback(new Error("请输入验证码"));
      } else if (validateVCode(value)) {
        return callback(new Error("输入的验证码格式有误"));
      } else {
        return callback();
      }
    };

    //菜单数据 reactive 用于对象类型数据
    const menuTab = reactive([
      { txt: "登录", current: true, type: "login" },
      { txt: "注册", current: false, type: "register" }
    ]);

    //表单数据
    const ruleForm = reactive({
      userName: "",
      code: "",
      password: "",
      passwords: ""
    });

    const rules = reactive({
      userName: [{ validator: validateUserName, trigger: "blur" }],
      password: [{ validator: validatePassword, trigger: "blur" }],
      passwords: [{ validator: validatePasswords, trigger: "blur" }],
      code: [{ validator: validateCode, trigger: "blur" }]
    });

    //设置获取验证码按钮的状态
    const getCodeStar = reactive({
      buttonName: "获取验证码",
      buttonSatr: false
    });

    //用于基本数据类型
    const mode = ref("login");
    //用于绑定当前的登陆按钮的禁用状态
    const loginButtonStart = ref(true);

    //用于记录定时器
    const countTime = ref(null);

    /**
     * 点击切换登陆注册
     */
    const toggleMenu = e => {
      // 重置登陆注册的数据
      refs.ruleForm.resetFields();

      menuTab.forEach(elem => {
        elem.current = false;
      });
      e.current = true;
      mode.value = e.type;

      // 切换状态时初始化数据
      loginButtonStart.value = true;
      clearCounDown();
      getCodeStar.buttonSatr = false;
      getCodeStar.buttonName = "获取验证码";
    };

    /**
     * 获取验证码
     */
    const getVerifyCode = () => {
      if (ruleForm.userName == "") {
        return root.$message({
          showClose: true,
          message: "邮箱不能为空哦～",
          type: "error"
        });
      }

      console.log(countTime);
      // 设置获取验证码button的状态
      getCodeStar.buttonSatr = true;
      getCodeStar.buttonName = "发送中...";

      let postData = { username: ruleForm.userName, module: mode.value };
      getSms(postData)
        .then(result => {
          root.$message({
            showClose: true,
            message: result.data.message,
            type: "success"
          });
          // 验证码获取成功之以后登陆按钮设置成可点击状态
          loginButtonStart.value = false;
          // 调用倒计时
          countdown(60);
        })
        .catch(err => {
          getCodeStar.buttonSatr = false;
          getCodeStar.buttonName = "重新发送";
          root.$message({
            showClose: true,
            message: err.data.message,
            type: "error"
          });
        });
    };

    /**
     * 设置倒计时
     */
    const countdown = time => {
      if (countTime.value) {
        // 清除定时器
        clearCounDown();
      }
      countTime.value = setInterval(() => {
        time--;
        getCodeStar.buttonName = `倒计时${time}秒`;
        getCodeStar.buttonSatr = true;
        if (time < 0) {
          time = 0;
          getCodeStar.buttonSatr = false;
          getCodeStar.buttonName = "重新发送";
          clearCounDown();
        }
      }, 1000);
    };

    /**
     * 清除定时器
     */
    const clearCounDown = () => {
      clearInterval(countTime.value);
    };

    /**
     * 提交用户输入信息
     */
    const submitForm = formName => {
      refs[formName].validate(valid => {
        if (valid) {
          let postData = {
            username: ruleForm.userName,
            password: sha1(ruleForm.password),
            code: ruleForm.code
          };
          mode.value == "login" ? userLogin(postData) : userRegister(postData);
        } else {
          return root.$message({
            showClose: true,
            message: "信息有误，请重新填写",
            type: "error"
          });
        }
      });
    };

    /**
     * 登陆
     */
    const userLogin = e => {
      root.$store
        .dispatch("loginStore", e)
        .then(() => {
          root.$router.replace({ name: "console", query: { id: "1" } });
        })
        .catch(err => {
          root.$message({
            showClose: true,
            message: err.message,
            type: "error"
          });
        });
    };

    /**
     * 注册
     */
    const userRegister = e => {
      register(e)
        .then(result => {
          root.$message({
            showClose: true,
            message: result.data.message,
            type: "success"
          });
          toggleMenu(menuTab[0]);
        })
        .catch(err => {
          root.$message({
            showClose: true,
            message: err.data.message,
            type: "error"
          });
        });
    };

    /**
     * 生命周期函数
     * 模块挂载完成
     */
    onMounted(() => {
      console.log(process.env.VUE_APP_NAME);
    });

    return {
      menuTab, //登陆注册
      mode, //当前是登陆还是注册的状态
      getCodeStar,
      loginButtonStart,
      ruleForm,
      rules,
      toggleMenu,
      getVerifyCode,
      submitForm
    };
  }
};
</script>

<style lang="scss" scoped>
#login {
  background-color: #344a5f;
  height: 100vh;
  .title {
    text-align: center;
    font-size: 32px;
    color: #fff;
    padding: 30px;
  }
}

.login-wrap {
  width: 330px;
  margin: auto;
}
.menu-tab {
  text-align: center;
  li {
    display: inline-block;
    width: 88px;
    line-height: 36px;
    font-size: 14px;
    color: #fff;
    border-radius: 2px;
    cursor: pointer;
  }
  .current {
    background-color: rgba(0, 0, 0, 0.1);
  }
}
.login-form {
  margin-bottom: 40px;
  label {
    color: #ffffff;
    font-size: 14px;
    margin-bottom: 3px;
  }
  .block {
    display: block;
    width: 100%;
  }
  .item-form {
    margin-bottom: 10px;
  }
  .login-button {
    margin-top: 20px;
  }
}
</style>
